<template>
  <div style="background:#f3f3f3">
    <header class="mint-header" style="font-size: 18px;">
      <div class="mint-header-button is-left">
        <button class="mint-button mint-button--default mint-button--normal" style="font-size: 15px;" @click="option">
          <span class="mint-button-icon">
            <i class="mintui mintui-back" />
          </span>
          <label class="mint-button-text">返回</label>
        </button>
      </div>
      <h1 class="mint-header-title">添加出车计划</h1>
      <div class="mint-header-button is-right" />
    </header>
    <div style="height:40px" />
    <mt-field v-model="usedetail" label="出车用途:" placeholder="输入出车用途" />
    <mt-field v-model="userid" label="司机:" style="z-index='999'" @input="click" />
    <picker :values="carid" :picdata="carlist" class="rd_picker" style="margin-left:-8px;" pictitle="*车辆牌照" @getpicval="getpicval" />
    <pickerdatetime :pictitle="'请选择开始时间'" :gettime.sync="grantime" :picdata="[]" :values="''" />
    <pickerdatetime :pictitle="'请选择结束时间'" :gettime.sync="endtime" :picdata="[]" :values="''" />
    <mt-field v-model="adrword" label="行车地点:" placeholder="请输入行车地点" />
    <!-- <uploadpic></uploadpic> -->
    <mt-button type="primary" style="width:100%;margin-top:20px" @click="gonuxt">确 定</mt-button>
    <div class="datePicker">
      <mt-datetime-picker ref="picker" :visible-item-count="5" type="datetime" year-format="{value} 年" month-format="{value} 月" date-format="{value} 日" @confirm="handleConfirm" />
    </div>
    <mt-popup v-model="showamap" position="left" class="mapcontent">
      <qqmap v-if="isRouterAlive" @changeshow="changeshow" />
    </mt-popup>
    <mt-popup v-model="popupVisible22" position="bottom" class="mint-popup" style="width:100%">
      <mt-picker :slots="dataList" :visible-item-count="5" :show-toolbar="true" value-key="cName" @change="onDateChange">
        <mt-button class="sure" style="display:block;position: absolute;
    right: 0px;" @click="handleConfirm2">确认</mt-button>
      </mt-picker>
    </mt-popup>
    <mt-popup v-model="popupVisible33" position="bottom" class="mint-popup" style="width:100%">
      <mt-picker :slots="dataList2" :visible-item-count="5" :show-toolbar="true" value-key="cName" @change="onDateChange2">
        <mt-button class="sure" style="display:block;position: absolute;
    right: 0px;" @click="handleConfirm3">确认</mt-button>
      </mt-picker>
    </mt-popup>
  </div>
</template>
<script>
import qqmap from '~/components/qqmap.vue'
import pickerdatetime from '~/components/pickerdatetime.vue'
import { formatDateMin } from '~/assets/formadata.js'
import wx from 'weixin-js-sdk'
import vueJsonp from 'vue-jsonp'
import picker from '~/components/picker.vue'
export default {
  components: {
    qqmap,
    pickerdatetime,
    picker
  },
  layout: 'default2',
  data () {
    return {
      showamap: false,
      popupVisible22: false,
      popupVisible33: false,
      adrword: '',
      isRouterAlive: false,
      popupVisible: false,
      equilist: [],
      userName: '',
      usedetail: '',
      city: '',
      dataList: [
        {
          flex: 1,
          values: [],
          className: 'slot1',
          textAlign: 'right'
        }
      ],
      input: {
        taskname: '任务1',
        tasklevel: '0',
        taskdate: '2020-06-10',
        context: 'renwuflsjk',
        charger: ['123', '345'],
        noticer: ['fss', 'vss']
      },
      dataList2: [
        {
          flex: 1,
          values: [],
          className: 'slot1',
          textAlign: 'right'
        }
      ],
      htitle: '添加出车计划',
      ts: this.newStore(),
      grantime: '请选择行车时间',
      endtime: '',
      mapdata: {},
      lat: '',
      lng: '',
      carid: '',
      chouseval: '',
      chousperson: '',
      chousname: [],
      chousname2: [],
      chouseid: '',
      chouseid2: '',
      dateval: {},
      wxinfo: {},
      cityname: '',
      addressdetail: '',
      userid: '',
      carlist: []
    }
  },
  mounted () {
    console.log(this.$jsonp, '000000')
    this.chouseval = '请选择牌照'
    this.chousperson = '请选择司机'
    this.loadpersons();
    var dateval = new Date()
    console.log(dateval, 'woshi')

    this.grantime = formatDateMin(dateval)
    // this.getWxConfig()
    this.getcarlist()

  },
  methods: {
    getpicval (val) {
      this.carid = val.showid
    },
    getcarlist () {
      const req = {
        handle: '0E56125B90D2898A62E387C1CED62EC408B04B35BD44D675',
        query: ''
      }
      this.spost(this.ts, '/mainservlet', req).then(ts => {
        ts.d.data.operation1.unshift({
          cols: ['carid', 'carno'],
          hash: { carno: '无', carid: '无' },
        });
        let a = []
        let item
        for (let index = 0; index < ts.d.data.operation1.length; index += 1) {
          let b = {}
          item = ts.d.data.operation1[index]
          b.showid = item.hash.carid
          b.showname = item.hash.carno
          a.push(b)
        }
        this.carlist = a
        console.log('11111')
      })
    },
    getWxConfig () {
      const res = {
        url: location.href.split('#')[0]
      }
      this.spost(this.ts, '/WeixinGetSignServlet', res).then(ts => {
        this.wxinfo = ts.d
        console.log(ts.d, '999')
        this.gowxconfig()
      })
    },
    //验证微信config
    gowxconfig () {
      //console.log(this.$jsonp, '000000')

      wx.config({
        debug: false,
        appId: this.wxinfo.appId,
        timestamp: this.wxinfo.timestamp,
        nonceStr: this.wxinfo.nonceStr,
        signature: this.wxinfo.signature,
        jsApiList: [
          // 所有要调用的 API 都要加到这个列表中
          'getLocation',
          'openLocation',
          'chooseImage',
          'previewImage',
          'uploadImage',
          'downloadImage',
          'getLocalImgData'
        ]
      })
      wx.ready(() => {
        wx.checkJsApi({
          jsApiList: ['getLocation'],

          success: res => {
            // alert(JSON.stringify(res));
            // console.log(res, '7777')
            // alert(JSON.stringify(res.checkResult.getLocation));
            if (res.checkResult.getLocation == false) {
              alert(
                '你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！'
              )
              return
            }
          }
        })
        wx.error(res => {
          //console.log(res)
          // alert(JSON.stringify(res))
        })
        wx.getLocation({
          success: res => {
            // alert(JSON.stringify(res))
            console.log(res, '6666')
            alert('')
            this.lat = res.latitude
            this.lng = res.longitude
            //console.log(this.hgdata)
            //console.log(this.lat, this.lng)

            // this.getCurrentCity(this.lng, this.lat)
            // console.log(this.getCurrentCity(this.lng, this.lat))
            this.$jsonp('http://apis.map.qq.com/ws/geocoder/v1/', {
              location: `${res.latitude},${res.longitude}`,
              coord_type: 5,
              key: 'STLBZ-YCKCG-AGGQK-IV3HY-6CKP2-LGBPM',
              output: 'jsonp',
              callback: 'calllocation'
            }).then(json => {
              let { address, formatted_addresses } = json.result
              console.log(json.result, '66666')
              this.cityname = json.result.address_component.city
              this.addressdetail = address
              //处理数据
            })
          },
          cancel: function (res) {
            // alert('用户拒绝授权获取地理位置')
            this.cityname = '无定位'
          }
        })
      })
    },
    handleConfirm2 () {
      document
        .getElementsByTagName('body')[0]
        .removeEventListener('touchmove', this.handler, { passive: false })
      //this.chouseval = this.$refs.picker.getValues()[0]
      this.popupVisible22 = false
    },
    handleConfirm3 () {
      document
        .getElementsByTagName('body')[0]
        .removeEventListener('touchmove', this.handler, { passive: false })
      //this.chouseval = this.$refs.picker.getValues()[0]
      this.popupVisible33 = false
    },
    onDateChange (picker, values) {
      console.log(picker, 123456)
      console.log(values, 123)
      this.chouseval = values
      for (let k = 0; k < this.chousname.length; k++) {
        if (this.chouseval == this.chousname[k].carno) {
          this.chouseid = this.chousname[k].carid
        }
      }
    },
    onDateChange2 (picker, values) {
      this.chousperson = values
    },
    loadpersons () {
      const req = {
        handle:
          '45EE8FEFE87870C53A0536D8566DA8C94345851CDDF60960CBCA139672EA5B8C230BE336D992C9E341DC33B3A5E90841',
        query: ''
      }
      this.spost(this.ts, '/mainservlet', req).then(ts => {
        let a = []
        let b = []
        for (let i = 0; i < ts.d.data.operation1.length; i++) {
          a.push(ts.d.data.operation1[i].hash.username)
          b.push(ts.d.data.operation1[i].hash)
        }
        this.dataList2[0].values = a
        this.chousname2 = b
      })
    },
    click (e) {
      console.log("aaaaaaaaaaaaaaa", e);
      this.chousperson = e;
      var pipei = false;
      for (let k = 0; k < this.chousname2.length; k++) {
        if (this.chousperson == this.chousname2[k].username) {
          console.log("匹配", 1111);
          this.chouseid2 = this.chousname2[k].pid
          pipei = true;
        }
      }
      if (!pipei) {
        this.chouseid2 = '';
      }
    },
    //添加牌照
    addcarid () {
      const req = {
        handle: '0E56125B90D2898A62E387C1CED62EC408B04B35BD44D675',
        query: ''
      }
      this.spost(this.ts, '/mainservlet', req).then(ts => {
        let a = []
        let b = []
        for (let i = 0; i < ts.d.data.operation1.length; i++) {
          a.push(ts.d.data.operation1[i].hash.carno)
          b.push(ts.d.data.operation1[i].hash)
          //a[m] = { carid: ts.d.data.operation1[m].hash.carno }
        }
        this.dataList[0].values = a
        this.chousname = b
        console.log(this.chousname, 'wwwww')
      })
      this.popupVisible22 = true
    },
    addtime () {
      this.$refs.picker.open()
    },
    handleConfirm (data) {
      //console.log(data)
      this.grantime = this.formatDate(data)
    },
    formatDate (date) {
      const y = date.getFullYear()
      let m = date.getMonth() + 1
      m = m < 10 ? '0' + m : m
      let d = date.getDate()
      d = d < 10 ? '0' + d : d
      let h = date.getHours()
      h = h < 10 ? '0' + h : h
      let mi = date.getMinutes()
      mi = mi < 10 ? '0' + mi : mi
      return y + '-' + m + '-' + d + ' ' + h + ':' + mi + ':00'
    },
    reload () {
      console.log('地图组件重新加载')

      this.isRouterAlive = false
      this.$nextTick(() => (this.isRouterAlive = true))
    },
    chooseadr () {
      this.reload()
      this.$nextTick(() => {
        this.showamap = true
      })
    },
    changeshow (data) {
      this.showamap1 = data
    },
    option () {
      this.$router.go(-1)
    },
    gonuxt () {
      if (this.carid == '' || this.carid == undefined) {
        this.$messagebox('提示', '请输入牌照')
        return
      }
      if (this.chouseid2 == '' || this.chouseid2 == undefined) {
        this.$messagebox('提示', '司机输入错误')
        return
      }
      if (this.usedetail == '' || this.usedetail == undefined) {
        this.$messagebox('提示', '请输入出车用途')
        return
      }
      if (this.grantime == '请选择开始时间' || this.grantime == undefined) {
        this.$messagebox('提示', '请选择行车时间')
        return
      }
      if (this.endtime == '请选择结束时间' || this.endtime == undefined) {
        this.$messagebox('提示', '请选择结束时间')
        return
      }
      if (this.adrword == '请选择行车地点' || this.adrword == undefined) {
        this.$messagebox('提示', '请选择行车地点')
        return
      }
      this.$messagebox.confirm('是否确认添加').then(action => {
        const req = {
          handle: '0E56125B90D2898A4A3BF7F51B00739F7E3D05C476FEFFCD',
          carid: this.carid,
          holder: this.chouseid2,
          plantime: this.grantime,
          usedetail: this.usedetail,
          address: this.adrword,
          recordtime_end: this.endtime
        }
        this.spost(this.ts, '/mainservlet', req).then(ts => {
          console.log(req, 'req')
          if (ts.d.sflag == 'success') {
            console.log(req, 'req')
            this.$messagebox('提示', '添加成功').then(action => {
              this.$router.push({
                name: 'carplan',
                query: {
                  name: '司机出车计划'
                }
              })
            })
          }
        })
      })
    }
  }
}
</script>
<style scoped>
.mint-cell-value .mint-field-core {
  text-align: right !important;
}
input .mint-field-core {
  text-align: right;
}
.picker-item {
  text-align: center !important;
}
.info-title {
  padding: 10px;
  color: #ccc;
  font-size: 16px;
}
html {
  background: #f3f3f3;
}
.equi-div {
  font-size: 12px;
  line-height: 20px;
  color: #969191;
}
.equi-shebei {
  display: inline-block;
  padding: 1px 10px;
  color: #fff !important;
  background: rgb(51, 51, 51);
}
.h3_equi {
  font-size: 16px;
  font-weight: 400;
  line-height: 40px;
}
.equi-span2 {
  width: calc(calc(100% / 2) - 10px);
}
.equi-div1 {
  font-size: 16px;
  line-height: 25px;
  /* margin: 0 10px; */
  /* border-bottom: 1px solid #ddd; */
  padding-bottom: 10px;
}
.equi-span {
  color: #35495e;
}
.equi-xq {
  line-height: 90px;
  /* padding-left: 20px; */
  color: #26a2ff;
  float: right;
  /* background: #ddd; */
  margin-top: 5px;
  width: 20%;
  text-align: center;
  border-left: 1px solid #ddd;
}
.equi-left {
  width: 100%;
  /* float: left; */
  padding-right: 0px;
  /* margin: 0 auto; */
  padding: 10px;
  background: #fff;
}
.mapcontent {
  width: 100%;
  height: 100%;
}
.mint-search {
  height: 7vh;
}
.mint-searchbar {
  background: #f3f3f3 !important;
}
</style>
